package cn.educate.servlet;

import cn.educate.service.FileClassifier;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/classify")
public class FileClassifierServlet extends HttpServlet {
    private static final Logger LOGGER = Logger.getLogger(FileClassifierServlet.class.getName());

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String sourceDir = request.getParameter("sourceDir");

        if (sourceDir == null || sourceDir.isEmpty()) {
            request.setAttribute("result", "源目录路径不能为空");
            request.getRequestDispatcher("index.jsp").forward(request, response);
            return;
        }

        File dir = new File(sourceDir);

        if (!dir.exists() || !dir.isDirectory()) {
            request.setAttribute("result", "指定的路径不是一个有效的目录");
            request.getRequestDispatcher("index.jsp").forward(request, response);
            return;
        }

        // 调用FileClassifier的classifyFiles方法
        FileClassifier.classifyFiles(sourceDir);

        // 构建结果字符串
        StringBuilder result = new StringBuilder();
        File[] extensionDirs = dir.listFiles(File::isDirectory);

        if (extensionDirs != null) {
            for (File extensionDir : extensionDirs) {
                String extension = extensionDir.getName().replace("Files", "");
                File[] filesInExtensionDir = extensionDir.listFiles();
                if (filesInExtensionDir != null) {
                    result.append("扩展名: ").append(extension).append(", 文件数量: ").append(filesInExtensionDir.length).append("\n");
                }
            }
        }

        request.setAttribute("result", result.toString());
        request.getRequestDispatcher("folder.jsp").forward(request, response);
    }
}
